package com.cloud.bc.controller.ajax.center;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.cloud.bc.model.domain.UserInfo;
import com.cloud.bc.model.entity.*;
import com.cloud.bc.model.enums.CodeEnum;
import com.cloud.bc.model.request.LikeRequest;
import com.cloud.bc.model.request.NearbyRequest;
import com.cloud.bc.model.request.SingleListRequest;
import com.cloud.bc.model.response.AjaxResp;
import com.cloud.bc.model.response.MomenSingleResponse;
import com.cloud.bc.model.response.SingleSearchResponse;
import com.cloud.bc.service.*;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
import java.util.Set;

@AllArgsConstructor
@RestController
@RequestMapping("m/ajax/center/single")
public class Ajax_SingleController {

    private final BcSinglesService bcSinglesService;
    private final BcSingleMatesService bcSingleMatesService;
    private final BcUsersService bcUsersService;
    //申请表
    private final BcContacapplysService bcContacapplysService;
    //同意表
    private final BcContactsService bcContactsService;
    private final BcSingleContactsService bcSingleContactsService;
    private final BcFriendApplysService bcFriendApplysService;
    private final BcFriendsService bcFriendsService;
    private final BcSingleLocationsService bcSingleLocationsService;

    @PostMapping("modify")
    public AjaxResp singleinfo(HttpServletRequest request,
                               HttpServletResponse response) {
        AjaxResp ajaxResp = new AjaxResp();
        UserInfo userInfo = bcUsersService.getUserInfo(request);
        if (null == userInfo || Convert.toInt(userInfo.getId()) <= 0) {
            ajaxResp.setMsg("当前状态未登录，请登录后重试");
            ajaxResp.setSuccess(false);
            return ajaxResp;
        }
        Map<String, String[]> parameterMap = request.getParameterMap();
        Set<String> keyList = parameterMap.keySet();
        String keyStr = "";
        String valueStr = "";
        for (String key : keyList) {
            if (key.equals("_d") || key.equals("_method")) {
                continue;
            }
            keyStr = key;
            String[] valueArr = parameterMap.get(key);
            String value = StrUtil.join(",", valueArr);
            valueStr = value;
        }
        //修改数据库
        bcSinglesService.setSingles(keyStr, valueStr, userInfo.getId());
        return ajaxResp;
    }

    @GetMapping("list")
    public AjaxResp list(HttpServletRequest request, HttpServletResponse response,
                         SingleListRequest req) {
        AjaxResp ajaxResp = new AjaxResp();
        Page page = new Page();
        page.setCurrent(Convert.toInt(req.getPage(), 1));
        page.setSize(10);
        List<SingleSearchResponse> listSingle = bcSinglesService.selectSingleSearch(page, req,request);
//        List<BcSingles> records = bcSinglesIPage.getRecords();
        ajaxResp.setList(listSingle);
        return ajaxResp;
    }

    /**
     * 申请联系方式
     */
    @GetMapping("apply_contact")
    public AjaxResp apply_contact(HttpServletRequest request, HttpServletResponse response,
                                  Integer reviewUserId) {
        AjaxResp ajaxResp = new AjaxResp();
        UserInfo userInfo = bcUsersService.getUserInfo(request);

        //查看是否好友
        int friendCount = bcFriendsService.existsFriend(userInfo.getId(), reviewUserId);
        if (friendCount <= 0) {
            //不是好友
            //查询是否在申请中的好友
            ajaxResp.setSuccess(false);
            ajaxResp.setMsg("与他还不是好友，请申请加为好友");
            ajaxResp.setCode(CodeEnum.FRIEND.getCode());
        }
        //查看同意表是否存在存在则直接返回
        BcContacts bcContacts = new BcContacts();
        bcContacts.setUserId(userInfo.getId());
        bcContacts.setTargetId(reviewUserId);
        int count = bcContactsService.count(bcContacts);
        if (count > 0) {
            //不为空则返回
            BcSingleContacts bcSingleContacts = new BcSingleContacts();
            bcSingleContacts.setUserId(reviewUserId);
            BcSingleContacts bcSingleContactsResult = bcSingleContactsService.selectOne(bcSingleContacts);
            if (null != bcSingleContactsResult) {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("user_id", reviewUserId);
                if (!StrUtil.isEmpty(bcSingleContactsResult.getEmail())) {
                    jsonObject.put("email", bcSingleContactsResult.getEmail());
                }
                if (!StrUtil.isEmpty(bcSingleContactsResult.getPhone())) {
                    jsonObject.put("phone", bcSingleContactsResult.getPhone());
                }
                if (!StrUtil.isEmpty(bcSingleContactsResult.getWechatid())) {
                    jsonObject.put("wechat", bcSingleContactsResult.getWechatid());
                }
                if (!StrUtil.isEmpty(bcSingleContactsResult.getQq())) {
                    jsonObject.put("qq", bcSingleContactsResult.getQq());
                }
                ajaxResp.setObj(jsonObject.toString());
                return ajaxResp;
            }
        }
        //申请联系方式
        BcContacapplys bcContacapplys = new BcContacapplys();
        bcContacapplys.setUserId(userInfo.getId());
        bcContacapplys.setTargetId(reviewUserId);
        int countApply = bcContacapplysService.count(bcContacapplys);
        if (countApply > 0) {
            //已经申请了
            //TODO 这时可以增加VIP验证
            ajaxResp.setSuccess(false);
            ajaxResp.setMsg("已经申请，请耐心等待");
            return ajaxResp;
        }
        bcContacapplys.setPaytype("setmeal");
        bcContacapplysService.save(bcContacapplys);
        return ajaxResp;
    }

    @GetMapping("contact")
    public AjaxResp contact(HttpServletRequest request, HttpServletResponse response,
                            LikeRequest req) {
        UserInfo userInfo = bcUsersService.getUserInfo(request);
//        type 2 申请看我，3我申请看的
        AjaxResp ajaxResp = new AjaxResp();
        Page page = new Page();
        page.setCurrent(req.getPage());
        page.setSize(5);
        BcContacapplys bcContacapplys = new BcContacapplys();
        if (req.getType().equals(3)) {
            bcContacapplys.setUserId(userInfo.getId());
        } else if (req.getType().equals(2)) {
            bcContacapplys.setTargetId(userInfo.getId());
        }
        IPage<BcContacapplys> bcContacapplysIPage = bcContacapplysService.selectPage(page, bcContacapplys);
        List<BcContacapplys> records = bcContacapplysIPage.getRecords();
        records.forEach(item -> {
            if (req.getType().equals(2)) {
                item.setSingle(bcSinglesService.selectOne(new BcSingles().setUserId(item.getTargetId())));
            } else if (req.getType().equals(3)) {
                item.setSingle(bcSinglesService.selectOne(new BcSingles().setUserId(item.getUserId())));
            }
        });
        ajaxResp.setList(records);
        return ajaxResp;
    }

    /**
     * 附近的人
     */
    @GetMapping("nearby")
    public AjaxResp nearby(HttpServletRequest request, HttpServletResponse response,
                           NearbyRequest req) {
        AjaxResp ajaxResp = new AjaxResp();
        UserInfo userInfo = bcUsersService.getUserInfo(request);

        //如果定位出问题就不返回了
        if (StrUtil.isEmpty(req.getLat())) {
            //坐标不存在
            ajaxResp.setMsg("请打开定位服务");
            ajaxResp.setSuccess(false);
            return ajaxResp;
        }
        BcSingleLocations bcSingleLocations = new BcSingleLocations();
        bcSingleLocations.setUserId(userInfo.getId());
        bcSingleLocations.setDistrictCn(req.getCity());
        bcSingleLocations.setLatitude(req.getLat());
        bcSingleLocations.setLongitude(req.getLng());
        bcSingleLocationsService.upsert(bcSingleLocations);

        //2根据坐标获取出最近排序用户
        Page page = new Page();
        page.setCurrent(req.getPage());
        req.setUserId(userInfo.getId());
        List<MomenSingleResponse> list = bcSinglesService.nearby(page, req);
        ajaxResp.setList(list);
        return ajaxResp;
    }

    /**
     * 完善信息第一步
     */
    @PostMapping("setup")
    public AjaxResp setup(HttpServletRequest request, HttpServletResponse response,
                          BcSingles req) {
        AjaxResp ajaxResp = new AjaxResp();
        UserInfo userInfo = bcUsersService.getUserInfo(request);

        req.setUserId(userInfo.getId());
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.eq("user_id", userInfo.getId());
        bcSinglesService.update(req, queryWrapper);
        if (!StrUtil.isEmpty(req.getPhone())) {
            //如果有联系方式
            BcSingleContacts bcSingleContacts = new BcSingleContacts();
            bcSingleContacts.setPhone(req.getPhone());
            bcSingleContacts.setUserId(req.getUserId());
            bcSingleContactsService.update(bcSingleContacts, queryWrapper);
        }
        return ajaxResp;
    }

    /**
     * PC更新单身信息
     */
    @PostMapping("pc_modify")
    public AjaxResp pcModify(HttpServletRequest request,
                             HttpServletResponse response,
                             BcSingles req) {
        AjaxResp ajaxResp = new AjaxResp();
        UserInfo userInfo = bcUsersService.getUserInfo(request);

        req.setUserId(userInfo.getId());
        boolean b = bcSinglesService.pcModify(request,response,req);
        ajaxResp.setSuccess(b);
        return ajaxResp;
    }
    /**
     * PC更新单身信息
     */
    @PostMapping("pc_modify_mate")
    public AjaxResp pcModifyMate(HttpServletRequest request,
                             HttpServletResponse response,
                             BcSingleMates req) {
        AjaxResp ajaxResp = new AjaxResp();
        UserInfo userInfo = bcUsersService.getUserInfo(request);

        req.setUserId(userInfo.getId());
        boolean b = bcSingleMatesService.pcModifyMate(req);
        ajaxResp.setSuccess(b);
        return ajaxResp;
    }
    //删除声音和视频
    @PostMapping("removeShow")
    public AjaxResp removeShow(HttpServletRequest request,
                                 HttpServletResponse response,
                                 BcSingles req) {
        AjaxResp ajaxResp = new AjaxResp();
        UserInfo userInfo = bcUsersService.getUserInfo(request);

        req.setUserId(userInfo.getId());
        boolean b = bcSinglesService.removeShow(req);
        ajaxResp.setSuccess(b);
        return ajaxResp;
    }
}
